package web;

import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //需求是添加联系人,所以需要获得add,jsp页面的所有参数,post请求含有中文数据需要解决乱码
        request.setCharacterEncoding("utf-8");
        //获取所有的数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //将数据封装到javabean中,使用内省技术(反射原理)
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
            UserService service = new UserServiceImpl();
            boolean boo = service.addUser(user);
            if (boo){
                response.sendRedirect("/queryListServlet");
            }else {
                response.sendRedirect("/error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
